//jqGrid的配置信息
$.jgrid.defaults.width = 1000;
$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

var baseURL = "../../";

//工具集合Tools
window.T = {};

// 获取请求参数
// 使用示例
// location.href = http://localhost:8080/index.html?id=123
// T.p('id') --> 123;
var url = function(name) {
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if(r!=null)return  unescape(r[2]); return null;
};
T.p = url;

//全局配置
$.ajaxSetup({
	dataType: "json",
	cache: false,
    complete : function(data){
        ajaxComplete(data);
    }
});

/**更新token*/
window.ajaxComplete = function(data){};

window.invalidAccess = function(){
    top.layer.alert('未登录或登录已超时',{
        title : '系统提示',
        area : ['300px','auto'],
        btnAlign: 'c',
        yes : function(index){
            layer.close(index);
            selfTopHref();
        },
        cancel : function(index,layero){
            layer.close(index);
            selfTopHref();
        }
    });
}

window.selfTopHref = function(){
    if(self==top){
        window.location.href = '/logout';
    }else{
        top.location.href = '/logout';
    }
};

function ajaxLoad(msg){
    msg = (msg == null || msg.length <= 0) ? '操作中,请稍候……' : msg;
    return top.layer.msg(msg,{icon:16,time:-1,shade:[0.3,'#000'],area:'auto'});
}

/**用法:addOrEdit('添加','#div_farm_dialog',['600px','400px'],function(index,layero){});*/
function addOrEdit(title,dom,area,callBak,btn3,btn3Call){
    var btns = (btn3 == null || btn3 == '') ? ['提交','取消'] : ['提交','取消',btn3];
   return layer.open({
       type : 1,
       title : title,
       content : $(dom),
       area : area || ['540px','480px'],
       btnAlign: 'c',
       resize : false,
       btn : btns,
       yes : function(index,layero){
           if(callBak){
               callBak(index,layero);
           }
       },
       btn3 : function(index,layero){
           if (btn3Call && btn3){
               btn3Call(index,layero);
           }
           return false;
       }
   });
}

//重写alert
window.alert = function(msg,callback){
    top.layer.alert(msg,{
        title : '系统提示',
        btnAlign: 'c',
        yes : function(index){
            top.layer.close(index);
            if(typeof(callback) === "function"){
                callback("ok");
            }
        },
        cancel : function(index,layero){
            top.layer.close(index);
            if(typeof(callback) === "function"){
                callback("ok");
            }
        }
    });
}

//列表的操作结果提示,dialogResult(data.msg);
window.dialogResult = function(msg){
    top.layer.alert(msg,{title:'系统提示',closeBtn:1,shade:0,time:1500,anim:2,offset:'rb',btn:null,});
}

//重写confirm式样框
window.confirm = function(msg, callback){
	top.layer.confirm(msg, {title : '系统提示',btn: ['确定','取消'],btnAlign: 'c'},
	function(index){//确定事件
		if(typeof(callback) === "function"){
            top.layer.close(index);
			callback("ok");
		}
	});
}

//选择一条记录
function getSelectedRow() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return;
    }
    var selectedIDs = grid.getGridParam("selarrrow");
    if(selectedIDs.length > 1){
    	alert("只能选择一条记录");
    	return ;
    }
    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
    	alert("请选择一条记录");
    	return ;
    }
    return grid.getGridParam("selarrrow");
}

//获取所选择的行的数据,若不指定key则整行数据
function getDataRow(field,dom){
    var grid = (dom == null || dom == undefined) ? $("#jqGrid") : $(dom) ;
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
        alert("请选择一条记录");
        return null;
    }
    var ids = grid.getGridParam("selarrrow");
    if(ids.length > 1){
        alert("只能选择一条记录");
        return null;
    }
    var id = $('#jqGrid').jqGrid('getGridParam','selrow');
    var rowData = $('#jqGrid').jqGrid('getRowData',id);
    if(field == null || field == undefined){
        return rowData;
    }else{
        return rowData[field];
    }
}

//判断是否为空
function isBlank(value) {
    return !value || !/\S/.test(value)
}
//下拉框
$.fn.bindSelect = function (options){
    var $element = $(this);
    if (options.url != "") {
        $.get(options.url+options.param, function(data){
            data=data.itemList;
            $.each(data, function (i) {
                $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]));
            });
            $element.on("change", function (e) {
                if (options.change != null) {
                    options.change(data[$(this).find("option:selected").index()]);
                }
                $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
            });
        });
    } else {
        $element.select2({
            minimumResultsForSearch: -1
        });
    }
};

/**自定义下拉列表,名字必须以$.fn.bindXxx的开头,但是在编辑时赋值有问题;用法:
 * dom <select id="educationId" class="form-control"></select>
 js $("#educationId").bindInitSelect({url:'',params:{pid:10},value:"kid",text:"text",selectText : '选择学历',change: function(object){}});
*/
$.fn.bindInitSelect = function (options){
    var $element = $(this);
    ajaxQuery(options.url,options.params,function(data){
        if(data.code == 0){
            data = data.data;
            $element.empty().append('<option value="">'+options.selectText+'</option>');
            $.each(data,function (i){
                $element.append($("<option></option>").val(data[i][options.value]).html(data[i][options.text]));
            });
            $element.on("change",function(e){
                if (options.change != null){
                    var obj = $("#"+$element.attr('id')+" option:selected");
                    options.change({value:obj.val(),text:obj.text()});
                }
            });
        }else{
            $element.empty().append('<option value="">'+data.msg+'</option>');
        }
    });
};

/**添加、删除、修改操作,body表体格式*/
window.ajaxExecute = function(url,params,succeed){
    var layerIndex = ajaxLoad('操作中,请稍候……');
    $.ajax({
        type : "POST",
        url : baseURL + url,
        contentType : "application/json",
        dataType : "json",
        data : params,
        success : function(data){
            parent.layer.close(layerIndex);
            if(data.code == 205){
                invalidAccess();
            }else if(data.code == 0){
                succeed(data);
            }else{
                alert(data.msg);
            }
        },
        error : function(response){
            alert('连接服务器失败');
        }
    });
};

/**添加、删除、修改操作,body表体格式,仅处理code=205,其余的自行处理*/
window.ajaxHandle = function(url,params,succeed){
    var layerIndex = ajaxLoad('操作中,请稍候……');
    $.ajax({
        type : "POST",
        url : baseURL + url,
        contentType : "application/json",
        dataType : "json",
        data : params,
        success : function(data){
            parent.layer.close(layerIndex);
            if(data.code == 205){
                invalidAccess();
            }else{
                succeed(data);
            }
        },
        error : function(response){
            alert('连接服务器失败');
        }
    });
};

/**带文件上传的表单提交*/
window.formSubmit = function(url,formData,succeed,error){
    var layerIndex = ajaxLoad('操作中,请稍候……');
    $.ajax({
        url : baseURL + url,
        type : "POST",
        data : formData,
        contentType : false,
        processData : false,
        dataType : "json",
        success : function(data){
            parent.layer.close(layerIndex);
            if(data.code == 205){
                invalidAccess();
            }else if(data.code == 0){
                succeed(data);
            }else{
                alert(data.msg);
            }
        },
        error : function (err){
            parent.layer.close(layerIndex);
            if(error){
                error(err);
            }else{
                alert('连接服务器失败');
            }
        }
    });
};

/**仅处理code=205,其余的自行处理*/
window.formHandle = function(url,formData,succeed,error){
    var layerIndex = ajaxLoad('操作中,请稍候……');
    $.ajax({
        url : baseURL + url,
        type : "POST",
        data : formData,
        contentType : false,
        processData : false,
        dataType : "json",
        success : function(data){
            parent.layer.close(layerIndex);
            if(data.code == 205){
                invalidAccess();
            }else{
                succeed(data);
            }
        },
        error : function (err){
            parent.layer.close(layerIndex);
            if(error){
                error(err);
            }else{
                alert('连接服务器失败');
            }
        }
    });
}

/**GET请求仅处理code=205,其余的自行处理;formGetHandle(url,{},function(data){});*/
window.formGetHandle = function(url,params,succeed,error){
    var layerIndex = ajaxLoad('操作中,请稍候……');
    $.ajax({
        type : "GET",
        url : baseURL + url,
        dataType : "json",
        data : params,
        success : function(data){
            parent.layer.close(layerIndex);
            if(data.code == 205){
                invalidAccess();
            }else{
                succeed(data);
            }
        },
        error : function (err){
            parent.layer.close(layerIndex);
            if(error){
                error(err);
            }else{
                alert('连接服务器失败');
            }
        }
    });
}

/**查询操作,仅作code=205的操作*/
window.ajaxQuery = function(url,params,succeed){
    var layerIndex = ajaxLoad('操作中,请稍候……');
    $.ajax({
        type : "GET",
        url : baseURL + url,
        dataType : "json",
        data : params,
        success : function(data){
            parent.layer.close(layerIndex);
            if(data.code == 205){
                invalidAccess();
            }else{
                succeed(data);
            }
        },
        error : function(response){
            alert('连接服务器失败');
        }
    });
};

/**查询操作,返回数据不带code和data的格式;url无需带前缀,仅作code=205的操作,用法:ajaxDataQuery('',{},function(data){});*/
window.ajaxDataQuery = function(url,params,succeed){
    var layerIndex = ajaxLoad('操作中,请稍候……');
    $.ajax({
        type : "GET",
        url : baseURL + url,
        dataType : "json",
        data : params,
        success : function(data){
            parent.layer.close(layerIndex);
            var _code = data.code
            if(_code){
                if(_code == 205){
                    invalidAccess();
                    return;
                }
            }
            succeed(data);
        },
        error : function(response){
            alert('连接服务器失败');
        }
    });
};

window.pageInfo = function(){
    if(window.innerHeight !== undefined){
        return {
            "width": window.innerWidth,
            "height": window.innerHeight
        }
    }else if(document.compatMode === "CSS1Compat"){
        return {
            "width": document.documentElement.clientWidth,
            "height": document.documentElement.clientHeight
        }
    }else{
        return {
            "width": document.body.clientWidth,
            "height": document.body.clientHeight
        }
    }
}

/**无需判断是否有值,即不需要 if(data == 0);setDataSelect('选择基地类型','#domId',data,'keyValue','keyText',111);*/
window.setDataSelect = function(defaultText,selectDom,data,value,showText,select){
    var htm = "<option value=''>"+defaultText+"</option>";
    if (data == null || data == '' || data == undefined || data.length <= 0){
        htm = "<option value=''>暂无选项</option>";
        $(selectDom).attr('disabled','disabled');
        $(selectDom).attr('title','暂无选项');
    } else {
        $(selectDom).attr('title',(defaultText == null || defaultText == '' || defaultText == undefined)?'选择选项':defaultText);
        for(var i=0;i<data.length;i++){
            htm+="<option value="+data[i][value]+">"+data[i][showText]+"</option>";
        }
        if($(selectDom).prop("disabled")){
            $(selectDom).prop("disabled",false);
        }
    }
    $(selectDom).html(htm);
    if(select != null && data.length > 0){
        for(var i=0;i<data.length;i++){
            if(data[i][value]==select){
                $(selectDom).val(select);
                break;
            }
        }
    }
}

//编辑时有问题,看能怎么解决?
window.viewTopDom = function(title,dom,area,callBak){
    top.layer.open({
        type : 1,
        title : title,
        shadeClose : false,
        area : area || ['600px','400px'],
        btn : ['提交','取消'],
        yes : function(index,layero){
            callBak(index,layero);
        },
        btnAlign : 'c',
        content : $(dom).html()//在最顶层显示
    });
}

window.viewDom = function(title,dom,area){
    top.layer.open({
        type : 1,
        title : title,
        closeBtn : 0,
        shadeClose : false,
        area : area || ['600px','400px'],
        btn : ['关闭'],
        btnAlign : 'c',
        content : $(dom).html()//在最顶层显示
    });
}

window.viewPage = function(title,url,area){
    $.get(baseURL + url,{},function(html){
        layer.open({
            type : 1,
            title : title,
            closeBtn : 0,
            shadeClose : false,
            area : area || ['600px','400px'],
            btn : ['关闭'],
            btnAlign : 'c',
            content : html
        });
    });
}